package com.hjt.upload;

import com.alibaba.fastjson.JSON;
import com.hjt.config.Config;
import com.hjt.model.MeterInfoDTO;
import com.hjt.model.UploadResultDTO;
import com.hjt.utils.EncryUtil;
import com.hjt.utils.LogUtil;
import org.tempuri.DTSSoapProxy;

import java.rmi.RemoteException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class UploadAction {
    private DTSSoapProxy service;

    public UploadAction() {
        service = new DTSSoapProxy();
    }

    public void doUpload(List<MeterInfoDTO> meters, Long collectionTime) {
        LogUtil.info("upload begin....");
        if (meters == null || meters.size() < 1) {
            LogUtil.info("upload no data....");
            return;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(collectionTime);
        LogUtil.info("upload data[" + Arrays.toString(meters.toArray()) + "]");
        Map<String, List<MeterInfoDTO>> group = meters.stream().collect(Collectors.groupingBy(MeterInfoDTO::getBuildingId));
        for (Map.Entry<String, List<MeterInfoDTO>> entry : group.entrySet()) {
            LogUtil.info("upload building[" + entry.getKey() + "]");
            String result = "";
            try {
                String xml = ProtocolXmlBuilder
                        .init(entry.getKey(), "01", "report")
                        .buildData(meters, "report", collectionTime)
                        .toXml();
                LogUtil.info("upload xml[" + xml + "]");
                String encrypt = EncryUtil.encrypt(xml, Config.secretKey, Config.encodeIv, EncryUtil.AES_CBC);
                result = service.transportEnergyData(entry.getKey(), calendar, encrypt);
                UploadResultDTO resultObj = JSON.parseObject(result, UploadResultDTO.class);
                if (UploadResultDTO.SUCCESS.equals(resultObj.getRESULT())) {
                    LogUtil.info("upload success");
                }else {
                    LogUtil.info("upload failed");
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            } finally {
                LogUtil.info("upload building end, result:" + result);
            }
        }
        LogUtil.info("upload end....");
    }
}
